// 加载express模块
const express=require('express')

// 加载https模块
const https = require('https');

// 加载http模块
const http = require('http');

// 加载fs模块
const fs=require('fs');

// cookie
const cookieParser = require('cookie-parser');

// 加载session
const session = require('express-session');

// 导入svg-captcha模块
const svgCaptcha = require('svg-captcha');

// 加载路由器模块
const kcRouter=require('./router/kc_router.js')

//加载bodyParser中间件
const bodyParser=require('body-parser')

//加载MD5模块
const md5 = require('md5');


// 创建服务器
const app=express();
const app2=express();

//引入CORS中间件
const cors=require('cors')
//使用CORS中间件
app2.use(cors(
	//  {
	// 服务器告诉浏览器
	// origin: [],
	//  credentials:true
//   }
));
// 引入网站证书
var privateKey  = fs.readFileSync('./public/Nginx/2_fantasyfuturex.com.key', 'utf8');
var certificate = fs.readFileSync('./public/Nginx/1_fantasyfuturex.com_bundle.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};

// 创建http和https服务器

//http服务器
var httpServer= http.createServer(app,function(){
	console.log('HTTP Server is running on: https://localhost:%s')
});

httpServer.listen(5003);

app.all("*", (req, res,next)=>{
	
	let host = req.headers.host;
	host = host.replace(/\:\d+$/, ''); // Remove port number
  	res.redirect(307, `https://${host}:5004${req.path}`);
	
});

//https服务器
var httpsServer = https.createServer(credentials, app2,function(){
	
	
	console.log('HTTPS Server is running on: https://localhost:%s');

	
});

httpsServer.listen(5004)



// 托管文件到静态资源
app2.use(express.static('./public'))

// 注入bodyParser中间件
app2.use(bodyParser.urlencoded({
	extended:false,
	}))

// 注入session
	// 使用express-session 来存放数据到session中
	app2.use(
		session({
			secret: 'keyboard cat',
			resave: false,
			saveUninitialized: true,
			cookie: { secure: false }
		})
	)

app2.get('/',(req,res,next)=>{
		
		res.sendFile('/public/index.html',{root:__dirname});
		   
	  });

// 挂载路由到
app2.use('/kc',kcRouter)
	  
//获取图片验证码
app2.get('/getcode', (req, res) => {
	const captcha = svgCaptcha.create({
		noise: 3, // 干扰线条的数量
		background: '#ff5033' // 背景颜色
	});
	// 将图片的验证码存入到 session 中
	req.session.img_code = captcha.text.toLocaleUpperCase() // 将验证码装换为大写
	console.log('存入session：'+req.session.img_code)
	res.type('svg');
	res.send(captcha.data);
});

// 注册时验证码中间件
app2.use('/kc/reg',(req,res,next) => {
	let yzm = req.body.yzm;
	console.log('从session取出：'+yzm);
	// img_code 获取传递的图片验证码 ,如果不相等，验证码错误
	   if(yzm.toLocaleUpperCase() == req.session.img_code){
		// res.send({code:200,message:"验证通过"})
		next()
	}else{
		res.send({code:202,message:"验证码错误"})
		}
})



//使用回调函数中间件获取错误
app2.use((error,req,res,next)=>{
	//后端打印错误
	console.log(error);
  
	//返回错误状态码和错误信息 显示为json对象
	res.send({code:502,msg:"服务器端错误"})
  })



